package com.mogician.len.activity;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import com.mogician.cropper.view.CropImageView;
import com.mogician.cropper.view.CropListener;
import com.mogician.len.R;
import com.mogician.len.util.PermissionUtil;
import com.mogician.len.util.PhotoUtil;

import java.io.IOException;
import java.security.Permission;

public class CropActivity extends AppCompatActivity
{
    Bitmap bitmap;
    private static final int REQUEST_PERMISSION = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_crop);

        Intent intent = getIntent();
        Uri imageUri = intent.getData();
        try
        {
            bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imageUri);
        } catch (IOException e)
        {
            e.printStackTrace();
        }

        final CropImageView cropImageView = findViewById(R.id.crop_image_view);
        cropImageView.setImageBitmap(bitmap);

        Button okBtn = findViewById(R.id.button_ok);

        final CropListener listener = newBitmap -> bitmap = newBitmap;

        okBtn.setOnClickListener(v->
        {
            cropImageView.crop(listener, true);
//            PermissionUtil.requestPermission(this,
//                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
//                    REQUEST_PERMISSION);

            Uri mediaUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            grantUriPermission(getPackageName(), mediaUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            Uri newUri = Uri.parse(MediaStore.Images.Media.insertImage
                    (getContentResolver(), bitmap, null,null));

//            Uri newUri = PhotoUtil.getUriFromBitmap(bitmap, this);
            Intent result = new Intent();
            result.setData(newUri);
            setResult(RESULT_OK, result);
            finish();
        });
    }

//    @Override
//    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults)
//    {
//        switch (requestCode)
//        {
//            case 1:
//                if(PermissionUtil.allGranted(this, grantResults))
//                {
//                    Uri newUri = Uri.parse(MediaStore.Images.Media.insertImage
//                            (getContentResolver(), bitmap, null,null));
//                    Intent result = new Intent();
//                    result.setData(newUri);
//                    setResult(RESULT_OK, result);
//                    finish();
//                }
//        }
//    }
}

